package client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Receives UDP-Messages and displays them.
 * 
 * @author Lukas
 *
 */
public class MessageReceiver implements Runnable {
	
	private final DatagramSocket socket;
	/**
	 * The user that is currently logged in / was at last logged in.
	 */
	public String user = ""; //just for the 'auction-ended'-notification
	
	/**
	 * @param port The port.
	 * @throws SocketException 
	 */
	public MessageReceiver(int port) throws SocketException {
		socket = new DatagramSocket(port);
	}

	@Override
	public void run() {
		try {
			for (;;) {
				DatagramPacket packet = new DatagramPacket(new byte[256], 256);
				socket.receive(packet);
				String received = new String(packet.getData(), 0, packet.getLength());
				Scanner sc = new Scanner(received);
				String type = sc.next();
				synchronized (user) {
					if (type.equals("!new-bid")) {
						System.out.println("\nYou have been overbid on '" + sc.nextLine().trim() + "'");
						System.out.print(user + ">: ");
					}
					if (type.equals("!auction-ended")) {
						String winner = sc.next();
						String amount = sc.next();
						String description = sc.nextLine().trim();
						String sign = ".";
						if (winner.equals(user)) {
							winner = "You";
							sign = "!";
						}
						System.out.println("\nThe auction '" + description + "' has ended. " + winner
								+ " won with " + amount + sign);
						System.out.print(user + ">: ");
					}
				}
			}
		} catch (IOException e) {
			System.out.println("Stop listening to server notifications");
		}
		socket.close();
	}
	
	/**
	 * Stops this thread.
	 */
	public void shutdown() {
		socket.close();
	}
}
